from datetime import datetime
from logging.handlers import RotatingFileHandler
import logging
from conf.setting import Setting

class LogOpertion:
    def __init__(self):
        self.setting=Setting()

    def creat_log(self):
        # 1.创建日志对象
        logger=logging.getLogger(__name__)
        logger.setLevel(self.setting.LOG_LEVEL)

        # 不存在处理器才会创建,避免重复生成多个处理器和格式器
        if not logger.handlers:

            # 2.文件处理器,输出到日志文件
            log_file_path=self.setting.LOG_PATH
            log_time=datetime.now().strftime('%Y%m%d_%H%M%S')
            log_file_name=log_file_path+r'\test_'+log_time+'.log'

            fh=RotatingFileHandler(filename=log_file_name,mode='a',backupCount=3,maxBytes=5242880)
            fh.setLevel(self.setting.LOG_LEVEL)

            # 3.控制台处理器
            sh=logging.StreamHandler()
            sh.setLevel(self.setting.LOG_LEVEL)
            # 4.设置格式器
            formatter=logging.Formatter(self.setting.LOG_FORMAT)

            fh.setFormatter(formatter)
            sh.setFormatter(formatter)
            logger.addHandler(fh)
            logger.addHandler(sh)

            return logger

# 提前创建日志器对象,调用时导入该对象,可实现:谁调用-->显示其哪个文件,方法,模块,调用的效果
logger=LogOpertion()
logs=logger.creat_log()

'''
# 每次调用 write_log 都会创建新处理器
def write_log(message):
    logger = LogOpertion()  # ⚠️ 每次创建新实例
    logger.creat_log().info(message)
'''
def write_log(message):
    #不创建LogOpertion对象改为直接调用LogOpertion()
    LogOpertion().creat_log().info(message)


if __name__ == '__main__':
    setting = Setting()
    log_file_path = setting.LOG_PATH
    log_time = datetime.now().strftime('%Y%m%d_%H%M%S')
    log_file_name = log_file_path + r'\test_' + log_time + '.log'
    print(log_file_name)